//
//  ApplyInfoViewController.swift
//  shaohuo
//
//  Created by my on 16/3/7.
//  Copyright © 2016年 lchenc3. All rights reserved.
//


import UIKit
import AliyunOSSiOS
import SwiftProgressHUD

enum ApplyInfoViewType: NSInteger {
    //  增加
    case add
    //  查看
    case show
    //  修改
    case update
}

class ApplyInfoViewController: UITableViewController {
    
    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var shenfenzhengTextField: UITextField!
    @IBOutlet weak var urgentTextField: UITextField!
    @IBOutlet weak var urgentMobileTextField: UITextField!
    @IBOutlet weak var gongjuLabel: UILabel!
    @IBOutlet weak var positiveButton: UIButton!
    @IBOutlet weak var backButton: UIButton!
    @IBOutlet weak var travelButton: UIButton!
    @IBOutlet weak var driveButton: UIButton!
    
    var buttonArray : Array<UIButton>!
    
    var viewActionType : ApplyInfoViewType = .add
    
    var dataPicker : UIPickerView!
    var datapickArray = ["不限","电动车","汽车","货车"]
    
    var tag : Int!
    
    var sendway_id = 0
    
    lazy var datePickerView : UIView = {
        () -> UIView in
        let pickerView = UIView(frame: CGRect(x: 0, y: kScreenHeight-300, width: kScreenWitdh, height: 300))
        pickerView.backgroundColor = UIColor(hexString: "#f4f4f4")
        let cancelButton = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 40))
        cancelButton.setTitle("取消", for: .normal)
        cancelButton.setTitleColor(UIColor.lightGray, for: .normal)
        cancelButton.addTarget(self, action: #selector(cancelBtnAction), for: .touchUpInside)
        let certainButton = UIButton(frame: CGRect(x: kScreenWitdh-60, y: 0, width: 60, height: 40))
        certainButton.setTitle("确定", for: .normal)
        certainButton.setTitleColor(UIColor(hexString: "#FE9C35"), for: .normal)
        certainButton.addTarget(self, action: #selector(certainBtnAction), for: .touchUpInside)
        dataPicker = UIPickerView(frame: CGRect(x: 0, y: 40, width: kScreenWitdh, height: 200))
        dataPicker.dataSource = self
        dataPicker.delegate = self
        pickerView.addSubview(cancelButton)
        pickerView.addSubview(certainButton)
        pickerView.addSubview(dataPicker)
        return pickerView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if viewActionType == .show {
            requesApplyInfo()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
    }
    
    //取消
    @objc func cancelBtnAction() {
        
        self.datePickerView.removeFromSuperview()
    }
    
    //确定
    @objc func certainBtnAction() {
        
        self.datePickerView.removeFromSuperview()
    }
    //提交
    @IBAction func submitBtnAction(_ sender: UIButton) {
        
        if nameTextField.text!.isEmpty {
            SwiftProgressHUD.showOnlyText("请输入真实姓名")
            return
        }
        
        if ValidatedType.IDCardIsValidated(vStr: shenfenzhengTextField.text!)==false {
            SwiftProgressHUD.showOnlyText("身份证号不合法")
            return
        }
        
        if urgentTextField.text!.isEmpty {
            SwiftProgressHUD.showOnlyText("请输入紧急联系人")
            return
        }
        
        if ValidatedType.PhoneNumberIsValidated(vStr: urgentMobileTextField.text!)==false{
            SwiftProgressHUD.showOnlyText("手机号不合法")
            return
        }
        
        switch sendway_id {
        case 0:
            if self.positiveButton.currentImage == nil||self.backButton.currentImage == nil {
                SwiftProgressHUD.showOnlyText("请上传身份证")
                return
            }
        case 1:
            if self.positiveButton.currentImage == nil||self.backButton.currentImage == nil {
                SwiftProgressHUD.showOnlyText("请上传身份证")
                return
            }
        case 2:
            if self.travelButton.currentImage == nil||self.driveButton.currentImage == nil {
                SwiftProgressHUD.showOnlyText("请上传行驶证和驾驶证")
                return
            }
        case 3:
            if self.travelButton.currentImage == nil||self.driveButton.currentImage == nil {
                SwiftProgressHUD.showOnlyText("请上传行驶证和驾驶证")
                return
            }
        default:
            break
        }
        
        let newImageArray = [self.positiveButton.currentBackgroundImage,self.backButton.currentBackgroundImage,self.travelButton.currentBackgroundImage,self.driveButton.currentBackgroundImage]
        
        //上传图片
        SwiftProgressHUD.showWait()
        OSSImageUploader.asyncUploadImages(newImageArray as! [UIImage], tempFolder: "applyData")  { (names, state) in
            DispatchQueue.main.async {
                if names?.count==2{
                    self.requesApplyAction(realname: self.nameTextField.text!, id_card: self.shenfenzhengTextField.text!, emergency_contact: self.urgentTextField.text!, emergency_contact_phone: self.urgentMobileTextField.text!, idcard_front: "/\((names![0]))", idcard_back: "/\((names![1]))", vehicle_license: "", driver_license:"", sendway_id:
                        "\(self.sendway_id)")
                }else if names?.count==4 {
                    self.requesApplyAction(realname: self.nameTextField.text!, id_card: self.shenfenzhengTextField.text!, emergency_contact: self.urgentTextField.text!, emergency_contact_phone: self.urgentMobileTextField.text!, idcard_front: "/\((names![0]))", idcard_back: "/\((names![1]))", vehicle_license: "/\((names![2]))", driver_license:"/\((names![3]))", sendway_id:
                        "\(self.sendway_id)")
                }
            }
            
        }
        
    }
    
    //选择证件照片
    @IBAction func uploadBtnAction(_ sender: UIButton) {
        
        tag = sender.tag
        //拍照
        let pickerController : UIImagePickerController =  UIImagePickerController()
        pickerController.allowsEditing = true
        pickerController.sourceType = .camera
        pickerController.delegate = self
        self.present(pickerController, animated: true, completion: nil)
        
    }
    
    func requesApplyAction(realname:String,id_card:String,emergency_contact:String,emergency_contact_phone:String,idcard_front:String,idcard_back:String,vehicle_license:String,driver_license:String,sendway_id:String) -> Void {
        
        //要加密的数据
        let param = ["command":"applyAction","uid":UserTicketModel.sharedInstance.uid ?? "","token":UserTicketModel.sharedInstance.token ?? "","realname":realname,"id_card":id_card,"emergency_contact":emergency_contact,"emergency_contact_phone":emergency_contact_phone,"idcard_front":idcard_front,"idcard_back":idcard_back,"vehicle_license":vehicle_license,"driver_license":driver_license,"sendway_id":sendway_id]
        
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Exam"], successed: { (resultDict) in
            
            SwiftProgressHUD.hideAllHUD()
            self.navigationController?.popViewController(animated: true)
            
        })
    }
    
    func requesApplyInfo() -> Void {
        
        //要加密的数据
        let param = ["command":"applyInfo","uid":UserTicketModel.sharedInstance.uid ?? "","token":UserTicketModel.sharedInstance.token ?? "","isfull":"1"]
        
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Exam"], successed: { (resultDict) in
            
            let data = resultDict["data"] as! [String:AnyObject]
            
            self.nameTextField.text = data["realname"] as? String
            self.shenfenzhengTextField.text = data["id_card"] as? String
            self.urgentTextField.text = data["emergency_contact"] as? String
            self.urgentMobileTextField.text = data["emergency_contact_phone"] as? String
            self.gongjuLabel.text = self.datapickArray[Int((data["sendway_id"] as? String)!)!]
            self.positiveButton.sd_setBackgroundImage(with: URL(string: "\(endpoint)/\(data["idcard_front"]!)"), for: .normal, completed: nil)
            self.backButton.sd_setBackgroundImage(with: URL(string: "\(endpoint)/\(data["idcard_back"]!)"), for: .normal, completed: nil)
            self.travelButton.sd_setBackgroundImage(with: URL(string: "\(endpoint)/\(data["vehicle_license"]!)"), for: .normal, completed: nil)
            self.driveButton.sd_setBackgroundImage(with: URL(string: "\(endpoint)/\(data["driver_license"]!)"), for: .normal, completed: nil)
            
        })
    }
}


extension ApplyInfoViewController {
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1{
            if indexPath.row == 0{
                UIApplication.shared.keyWindow?.addSubview(self.datePickerView)
            }
        }
    }
    
//    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        return 20
//    }

    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
}


extension ApplyInfoViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let newPhoto = info[UIImagePickerControllerEditedImage] as! UIImage
        picker.dismiss(animated: true, completion: nil)
        
        switch tag {
        case 100:
            self.positiveButton.setBackgroundImage(newPhoto, for: .normal)
        case 101:
            self.backButton.setBackgroundImage(newPhoto, for: .normal)
        case 102:
            self.travelButton.setBackgroundImage(newPhoto, for: .normal)
        case 103:
            self.driveButton.setBackgroundImage(newPhoto, for: .normal)
        default:
            break
        }
    }
}

extension ApplyInfoViewController:UIPickerViewDataSource,UIPickerViewDelegate {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.datapickArray.count
    }
    
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return self.datapickArray[row]
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.sendway_id = row
        self.gongjuLabel.text = self.datapickArray[row]
    }
    
}


